'use strict';

var Router = require('koa-router');
var config = require('../../../config/index.js');
var dao = require('../../../dao/face_star.js');
var appUtil = require('../../../common/app_utils.js');
var errCodes = require('../../../common/err_code.js');

//
var __pathPrefix = config.manBaseUrl + '/v1/face/star';
appUtil.appLog('router:' + __pathPrefix);
var router = new Router({prefix: __pathPrefix});
module.exports = router.routes();

var counter = require('../../../dao/counter.js');
var myCounter = counter.bindCounter(counter.TypesEnum.faceStar);
/**
 * 上传明星脸
 * post /api/v1/face/star/upload
 * uid=111
 * name=明星名字
 * files.face=[object]
 */
router.post('/upload', function*() {
  var fields = this.request.inParams.fields;
  var files = this.request.inParams.files;
  var faceFile = files && files.face;
  var name = fields.name;
  if (!faceFile) {
    return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, 'face文件');
  }
  if (!name) {
    return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, 'name');
  }

  // 保存文件,保存记录到数据库
  var starid = yield myCounter();
  var pathResult = appUtil.getPath_starFace(faceFile.path, starid);
  appUtil.moveFile(faceFile.path, pathResult.fullPath);
  var result = yield dao.save({starid: starid, name: name, path: pathResult.fullPath, rpath: pathResult.rpath});
  this.body = appUtil.fout({
    name: result.name,
    starid: result.starid
  });
});

/**
 * 获取所有明星
 * get /api/v1/face/star/list?token=%token
 * 是为了支持 token校验
 */
router.get('/list', function*() {
  //var uid = this.request.inParams.fields.uid;

  var result = yield dao.getAll();
  var ret = [];
  for (var item of result) {
    ret.push({
      name: item.name,
      starid: item.starid,
      url: config.rootUrl + item.rpath
    });
  }
  this.body = appUtil.fout(ret);
});

/**
 * 编辑明星
 * post /api/v1/face/star/edit
 * 是为了支持 token校验
 */
router.post('/edit', function*() {
  var starid = this.request.inParams.fields.starid;
  var name = this.request.inParams.fields.name;
  if (!starid) {
    return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, 'starid');
  }
  if (!name) {
    return this.body = appUtil.ferror(errCodes.E_ARGS_INVALID, 'name');
  }

  var result = yield dao.updateName(starid, name);
  this.body = appUtil.fout(result);
});